#include <openssl/evp.h>
#include <stdio.h>
#include <stdlib.h>

int sm4_encrypt(const unsigned char *plaintext, int plaintext_len, const unsigned char *key, unsigned char *ciphertext) {
    EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
    int len;
    int ciphertext_len = 0;
    if (EVP_EncryptInit_ex(ctx, EVP_sm4_ecb(), NULL, key, NULL) != 1)
        goto err;
    if (EVP_EncryptUpdate(ctx, ciphertext, &len, plaintext, plaintext_len) != 1)
        goto err;
    ciphertext_len = len;
    if (EVP_EncryptFinal_ex(ctx, ciphertext + len, &len) != 1)
        goto err;
    ciphertext_len += len;
err:
    EVP_CIPHER_CTX_free(ctx);
    return ciphertext_len;
}

int sm4_decrypt(const unsigned char *ciphertext, int ciphertext_len, const unsigned char *key, unsigned char *plaintext) {
    EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
    int len;
    int plaintext_len = 0;
    if (EVP_DecryptInit_ex(ctx, EVP_sm4_ecb(), NULL, key, NULL) != 1)
        goto err;
    if (EVP_DecryptUpdate(ctx, plaintext, &len, ciphertext, ciphertext_len) != 1)
        goto err;
    plaintext_len = len;
    if (EVP_DecryptFinal_ex(ctx, plaintext + len, &len) != 1)
        goto err;
    plaintext_len += len;
err:
    EVP_CIPHER_CTX_free(ctx);
    return plaintext_len;
}
